import {
  ActionType,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable
} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, Drawer, message, Popconfirm} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import type {SortOrder} from 'antd/es/table/interface';
import {addBorrowRecordUsingPost} from "@/services/backend/borrowRecordController";
import {listBookVoByPageUsingPost} from "@/services/backend/bookController";
import {listCategoryUsingGet} from "@/services/backend/categoryController";


const TableList: React.FC = () => {

  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.BookVO>();
  const actionRef = useRef<ActionType>();

  const [valueEnum, setValueEnum] = useState<Record<string, any>>();
  const [openConfirm, setOpenConfirm] = useState<boolean>(false);

  const fetchData = async () => {

    const res = await listCategoryUsingGet();
    if (res && res.code === 0 && res.data) {
      const userMaps = new Map();
      for (const category of res.data) {
        const categoryMap = new Map([["", category.name]]);
        userMaps.set(category.id, categoryMap);
      }
      setValueEnum(userMaps);
    } /*else {
      message.error("分类信息获取失败-" + (res?.message || "未知错误"));
    }*/
  }
  useEffect(() => {
    fetchData()
  }, []);

  /**
   *  Delete node
   * @zh-CN 借阅节点
   *
   * @param record
   */
  const handleBorrow = async (record: API.BookVO) => {
    const hide = message.loading('正在借阅');
    if (!record) return true;
    try {
      const res = await addBorrowRecordUsingPost({bookId: record.id});
      hide();
      if (res.code === 0)
        message.success('借阅成功');
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('借阅失败，' + error.message);
      return false;
    }
  };

  const columns: ProColumns<API.BookVO>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      valueType: 'index',
      width: 50,
      hideInTable: true,
    },
    {
      title: '书名',
      dataIndex: 'title',
      valueType: 'text',
    },
    {
      title: '作者',
      dataIndex: 'author',
      valueType: 'text',
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
    },
    {
      title: '分类',
      dataIndex: 'categoryId',
      valueType: 'text',
      valueEnum: valueEnum,
      order: 100,
      hideInTable: true,
      // hideInTable: true,
    },
    {
      title: '剩余量',
      dataIndex: 'inventory',
      valueType: 'text',
      sorter: true,
      search: false,
      hideInTable: true,
    },
    {
      title: '出版社',
      dataIndex: 'publisher',
      valueType: 'text',
      hideInTable: true,
    },
    {
      title: '价格',
      dataIndex: 'price',
      valueType: 'money',
      search: false,
      hideInTable: true,
    },
    {
      title: '出版日期',
      dataIndex: 'publishDate',
      valueType: 'date',
      hideInTable: true,
      search: false,
    },
    /*{
      title: '性别',
      dataIndex: 'gender',
      valueType: 'text',
      width: 50,
      valueEnum: new Map([
        [1, '女'],
        [0, '男'],
      ]),
    },*/
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => [
        <Popconfirm
          key="borrow"
          title="你确认借阅吗"
          disabled={openConfirm}
          onConfirm={() => {
            handleBorrow(record);
            setOpenConfirm(false)
          }}
          onCancel={() => {
            setOpenConfirm(false)
          }}
        >
          <Button type={'text'}
                  size={'small'}
                  danger
                  key="borrowBtn"
                  onClick={() => {
                    setOpenConfirm(true)
                  }}
          >
            借阅
          </Button>
        </Popconfirm>,
        // <Button
        //   type={'text'}
        //   size={'small'}
        //   danger
        //   key="borrow"
        //
        // >
        //   借阅
        // </Button>,
        <Button
          type={'text'}
          size={'small'}
          key="show"
          onClick={() => {
            setShowDetail(true)
            setCurrentRow(record);
          }}
        >
          详情
        </Button>
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        // headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey={currentRow?.id?.toString() || undefined}
        search={{
          labelWidth: 120,
        }}
        // dataSource={categoryList}
        toolBarRender={() => []}
        // @ts-ignore
        request={async (
          params: {
            pageSize?: number | undefined;
            current?: number | undefined;
            keyword?: string | undefined;
          },
          sort: Record<string, SortOrder>,
          // sort: any,
          filter: Record<string, React.ReactText[] | null>,
        ) => {
          // console.log(sort)
          let sortFieldStr = "";
          let sortOrderStr: any;
          if (Object.keys(sort).length > 0) {
            const [firstSort] = Object.entries(sort); // 获取sort对象的第一个键值对
            sortFieldStr = firstSort[0];
            sortOrderStr = firstSort[1];
          }
          const res = await listBookVoByPageUsingPost({
            ...params,
            sortField: sortFieldStr,
            sortOrder: sortOrderStr,
          });
          if (res?.data) {
            return {
              data: res?.data.records || [],
              success: true,
              total: res?.data.total,
            };
          } else {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        // @ts-ignore
        columns={columns}
      />

      <Drawer
        width={300}
        open={showDetail}
        // visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
        title={"详情"}
      >
        <ProDescriptions
          column={1}
          title={"详细信息"}
          request={async () => ({
            data: currentRow || {},
          })}
          // dataSource={{currentRow} || {}}
          params={{
            id: currentRow?.id,
          }}
          columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
        />
        <Button onClick={() => {
          setShowDetail(false)
        }} type={"primary"}>关闭</Button>
      </Drawer>

    </PageContainer>
  );
};
export default TableList;
